package org.shiro.service.Impl;

import org.shiro.dao.UserRoleMapper;
import org.shiro.entity.UserRole;
import org.shiro.service.UserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.List;

/** @author HKC */
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
@Service
public class UserRoleServiceImpl implements UserRoleService {
  @Autowired private UserRoleMapper userRoleMapper;

  @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
  @Override
  public List<UserRole> queryByUserId(Long userId) {
    Assert.notNull(userId, "参数错误");
    List<UserRole> userRoleList = userRoleMapper.queryByUserId(userId);
    if (userRoleList != null && userRoleList.size() > 0) {
      return userRoleList;
    }
    return null;
  }

  @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
  @Override
  public int insertRoles(Long userId, List<Long> roleIds) {
    Assert.notNull(userId, "参数错误");
    Assert.notNull(roleIds, "参数错误");
    int res = userRoleMapper.insertRoles(userId, roleIds);
    if (res > 0) {
      return res;
    }
    return 0;
  }

  @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
  @Override
  public int insertUsers(Long roleId, List<Long> userIds) {
    Assert.notNull(userIds, "参数错误");
    Assert.notNull(roleId, "参数错误");
    int res = userRoleMapper.insertUsers(roleId, userIds);
    if (res > 0) {
      return res;
    }
    return 0;
  }

  @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
  @Override
  public int removeByUserId(Long userId) {
    Assert.notNull(userId, "参数错误");
    int res = userRoleMapper.deleteByUserId(userId);
    if (res > 0) {
      return res;
    }
    return 0;
  }

  @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
  @Override
  public int create(Long userId, Long roleId) {
    Assert.notNull(userId, "参数错误");
    Assert.notNull(roleId, "参数错误");
    int res = userRoleMapper.insertSelective(userId, roleId);
    if (res > 0) {
      return res;
    }
    return 0;
  }
}
